package com.colin.app.pay.ali;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;

import com.alipay.sdk.app.AuthTask;
import com.alipay.sdk.app.PayTask;
import com.colin.app.pay.ali.bean.AuthResult;
import com.colin.app.pay.ali.bean.PayResult;
import com.colin.app.pay.ali.utils.OrderInfoUtil2_0;
import com.colin.app.pay.callback.IPayListener;
import com.colin.library.help.LogHelp;

import java.util.Map;


/**
 * Created by ColinLu on 2016/9/8.
 */
public class ALiPayUtil {
    /**
     * 支付宝支付业务：入参app_id
     */
    public static final String APPID = "2013081700024223";

    /**
     * 支付宝账户登录授权业务：入参pid值
     */
    public static final String PID = "2088102123816631";
    /**
     * 支付宝账户登录授权业务：入参target_id值
     */
    public static final String TARGET_ID = "kkkkk091125";
    /**
     * 商户私钥，pkcs8格式
     */
    public static final String RSA_PRIVATE = "MIICXQIBAAKBgQDZqF0csSYYH45nUpD0UnnEerVgJpP1f6BOTNlL1yJG2H4xx/wyYgqvTj+BsBrueM1GcGQckALYlkaHLym1Ys4RkHSYEJi6Iw65P+AHj59kbUSpbMH27lnuz6S54UC+kYjJqNUiDlzx6dLsAvtyjDu8DD1ShKbHkuKcTWMhF4rMwQIDAQABAoGBAKf2oxQXKHyJLY1STAYe91TGFN2EJ73VpVGHQFCkThE50/h6iYYf3nr1+VANJFtO4aov5TGdeHTHUtnTbW5KNxYty4PSwSFMC/ADlgrD57LJD5eSG7mk6jk8+pc6lA/yUjT7v0L0h6ekO46edMAFh6Yp31E3Cg7PXhk0ItFdiqK5AkEA+y15AbPYg3PqK4ylREp8RJXJu6Ca1qyCMsCuvJb+2SWCRL08vPRXEDc3nwy3pQ2lIMGfQzgYtsgBEWEWWZIp1wJBAN3WJFI49YVWXzGdECPbURkhjYIzNY7itw6aGTBpBmHehOc+45aAFMBDKGN4VH/mHwLclEuXFnrE8joTAHbxWycCQFpgcULgkE40PhTvZWPeHTqcXtrpHe2SYsKaPAVVm1tMuMO9B4bBsDYAeD39WHLGJx1TLdgE7jeOXXwAYAdYpT8CQQCzjWEmn+2xt8AjEyJ+M0TH142HBdXiygQqsHWU5l0BGC9wUEm7hf3FxFXLdRjH0MXm9gydxjOuuPvqH3kvzJjfAkBHWiR3DaDpr2LcEsDeoGLVYEGNFKQFvOGvIACeO1vM3oSHZIfucTAi8eRa+YAHr6l/9G47l5tXYDpN20EpR4MC";


    private static ALiPayUtil instance = null;


    private ALiPayUtil() {
    }

    public static class Holder {
        static ALiPayUtil instance = new ALiPayUtil();
    }

    public static ALiPayUtil getInstance() {
        return Holder.instance;
    }


    private IPayListener mListener = null;
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    @SuppressLint("HandlerLeak")
    @SuppressWarnings("unchecked")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    LogHelp.e(payResult.toString());
                    // 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        if (mListener != null) {
                            mListener.payCallBack(IPayListener.SUCCESS, "支付成功");
                        }
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        if (mListener != null) {
                            mListener.payCallBack(IPayListener.FAIL, "支付失败");
                        }
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    LogHelp.e(authResult.toString());
                    String resultStatus = authResult.getResultStatus();
                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        if (mListener != null) {
                            mListener.payCallBack(IPayListener.SUCCESS, "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()));
                        }
                    } else {
                        // 其他状态值则为授权失败
                        if (mListener != null) {
                            mListener.payCallBack(IPayListener.FAIL, "授权失败" + String.format("authCode:%s", authResult.getAuthCode()));
                        }
                    }
                    break;
                }
            }
        }

    };


    /**
     * get the sdk version. 获取SDK版本号
     */
    public void getSDKVersion(Activity mActivity, IPayListener mListener) {
        PayTask payTask = new PayTask(mActivity);
        String version = payTask.getVersion();
        if (mListener != null) {
            mListener.payCallBack(IPayListener.OTHER, version);
        }
    }

    /**
     * 支付
     *
     * @param object
     * @param mListener
     */
    public void pay(Activity mActivity, Object object, IPayListener mListener) {
        if (parameterIsOk(mActivity)) {
            /**
             * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
             * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
             * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
             *
             * orderInfo的获取必须来自服务端；
             */
            Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID);
            String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
            String sign = OrderInfoUtil2_0.getSign(params, RSA_PRIVATE);
            String orderInfo = orderParam + "&" + sign;
            //开启子线程
            this.mListener = mListener;
            new Thread(new PayRunnable(mActivity, orderInfo)).start();
        }
    }

    /**
     * 原生的H5（手机网页版支付切natvie支付） 【对应页面网页支付按钮】
     */
    public void h5Pay(Activity mActivity, String url) {
        Intent intent = new Intent(mActivity, H5PayDemoActivity.class);
        Bundle extras = new Bundle();
        /**
         * url是测试的网站，在app内部打开页面是基于webview打开的，demo中的webview是H5PayDemoActivity，
         * demo中拦截url进行支付的逻辑是在H5PayDemoActivity中shouldOverrideUrlLoading方法实现，
         * 商户可以根据自己的需求来实现
         */
//        String url = "http://m.taobao.com";
        // url可以是一号店或者淘宝等第三方的购物wap站点，在该网站的支付过程中，支付宝sdk完成拦截支付
        extras.putString("url", url);
        intent.putExtras(extras);
        mActivity.startActivity(intent);
    }

    /**
     * 授权
     *
     * @param object
     * @param mListener
     */
    public void auth(Activity mActivity, Object object, IPayListener mListener) {
        if (isAuthParameterOk(mActivity)) {
            /**
             * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
             * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
             * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
             *
             * authInfo的获取必须来自服务端；
             */
            Map<String, String> authInfoMap = OrderInfoUtil2_0.buildAuthInfoMap(PID, APPID, TARGET_ID);
            String info = OrderInfoUtil2_0.buildOrderParam(authInfoMap);
            String sign = OrderInfoUtil2_0.getSign(authInfoMap, RSA_PRIVATE);
            String authInfo = info + "&" + sign;
            // 必须异步调用
            this.mListener = mListener;
            new Thread(new AuthRunnable(mActivity, authInfo)).start();
        }

    }

    private boolean parameterIsOk(Activity mActivity) {
        if (TextUtils.isEmpty(APPID)) {
            toast(mActivity, "APPID配置不能为空");
            return false;
        }
        if (TextUtils.isEmpty(RSA_PRIVATE)) {
            toast(mActivity, "RSA_PRIVATE配置不能为空");
            return false;
        }
        return !TextUtils.isEmpty(RSA_PRIVATE) && !TextUtils.isEmpty(APPID);
    }

    private void toast(Activity mActivity, String msg) {
        Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT).show();
    }

    private boolean isAuthParameterOk(Activity mActivity) {
        if (TextUtils.isEmpty(PID)) {
            toast(mActivity, "PIDD配置不能为空");
            return false;
        }
        if (TextUtils.isEmpty(APPID)) {
            toast(mActivity, "APPID配置不能为空");
            return false;
        }
        if (TextUtils.isEmpty(RSA_PRIVATE)) {
            toast(mActivity, "RSA_PRIVATE配置不能为空");
            return false;
        }
        if (TextUtils.isEmpty(TARGET_ID)) {
            toast(mActivity, "TARGET_ID配置不能为空");
            return false;
        }
        return !TextUtils.isEmpty(PID) && !TextUtils.isEmpty(APPID) && !TextUtils.isEmpty(RSA_PRIVATE) && !TextUtils.isEmpty(TARGET_ID);
    }

    private class PayRunnable implements Runnable {
        private Activity mActivity;
        private String orderInfo;

        public PayRunnable(Activity mActivity, String orderInfo) {
            this.mActivity = mActivity;
            this.orderInfo = orderInfo;
        }

        @Override
        public void run() {
            PayTask alipay = new PayTask(mActivity);
            Map<String, String> result = alipay.payV2(orderInfo, true);
            LogHelp.e(result.toString());
            Message msg = new Message();
            msg.what = SDK_PAY_FLAG;
            msg.obj = result;
            mHandler.sendMessage(msg);
        }
    }

    private class AuthRunnable implements Runnable {
        private Activity mActivity;
        private String authInfo;

        public AuthRunnable(Activity mActivity, String authInfo) {
            this.mActivity = mActivity;
            this.authInfo = authInfo;
        }

        @Override
        public void run() {
            // 构造AuthTask 对象
            AuthTask authTask = new AuthTask(mActivity);
            // 调用授权接口，获取授权结果
            Map<String, String> result = authTask.authV2(authInfo, true);

            Message msg = new Message();
            msg.what = SDK_AUTH_FLAG;
            msg.obj = result;
            mHandler.sendMessage(msg);
        }
    }
}
